const express = require('express')
const path = require("path")
const bodyParser = require('body-parser')

const constant = require('./utils/constant')

const app = express()
const port = 3000

// body parser
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))

// CORS & Preflight request
app.use((req, res, next) => {
  if (req.path !== '/' && !req.path.includes('.')) {
    res.set({
      'Access-Control-Allow-Credentials': true,
      'Access-Control-Allow-Origin': req.headers.origin || '*',
      'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
      'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
      'Content-Type': 'application/json; charset=utf-8',
    })
  }
  req.method === 'OPTIONS' ? res.status(204).end() : next()
})

// 其他中间件和配置...

// 引入路由模块
const modules = require('./modules/index')

// 设置静态文件目录
app.use('/' + constant.UPLOADS_PATH, express.static(path.join(__dirname, constant.UPLOADS_PATH)))
app.use('/' + constant.CHUNKS_PATH, express.static(path.join(__dirname, constant.CHUNKS_PATH)));

// 使用路由模块
modules.forEach(route => {
  app.use(route.routeName, route.route)
})


app.listen(port, () => {
  console.log(`
  服务已启动：
  
  http://localhost:${port}
  `)
})
